#include <iostream>
#include <unistd.h>
#include "bike.pb.h"
#include "ievent.h"
#include "iniconfig.h"
#include "logger.h"
#include "events_def.h"
#include "user_event_handler.h"
#include "DispatchMsgService.h"
#include "NetworkInterface.h"
#include "sqlconnection.h"
#include "BusProcessor.h"

using namespace std;             

int main(int argc, char** argv)
{
	if (argc != 3) {
		printf("Please input shbk<config file path><log file config>!\n");
		return -1;
	}
	// 初始化log4cpp
	if (!Logger::instance()->init(std::string(argv[2]))) {
		fprintf(stderr, "init log moude failed.\n");
		return -2;
	}

	// 读取配置文件
	Iniconfig* config = Iniconfig::getInstance();
	if (!config->loadfile(argv[1])) {
		printf("load %s failed.\n", argv[1]);
		LOG_ERROR("load %s failed.", argv[1]);
		Logger::instance()->GetHandle()->error("load %s failed.", argv[1]);
		return -3;
	}
	st_env_config config_args = config->getconfig();

	LOG_INFO("[DATABASE] ip: %s port: %d user: %s pwd: %s db: %s [server] port: %d\n", 
		config_args.db_ip.c_str(), config_args.db_port, config_args.db_user.c_str(), config_args.db_pwd.c_str(),config_args.db_name.c_str(),
		config_args.svr_port);

	//MysqlConnection mysqlConn;
	std::shared_ptr<MysqlConnection> mysqlConn = std::make_shared<MysqlConnection>();
	bool ret = mysqlConn->Init(config_args.db_ip.c_str(), config_args.db_port, config_args.db_user.c_str(),
		config_args.db_pwd.c_str(), config_args.db_name.c_str());

	if (!ret) {
		LOG_ERROR("init mysql is failed . exit!");
		return -4;
	}

	BusinessProcessor busPro(mysqlConn);
	busPro.init();//注册事件
	//MobileCodeReqEv mobile("15502383072");
	//UserEventHandler uehl;
	//uehl.handle(&mobile);

	DispatchMsgService* DMS = DispatchMsgService::getInstance();
	DMS->open();//创建线程池

	NetworkInterface* NTIF = new NetworkInterface();
	ret = NTIF->start(config_args.svr_port);// 启动网络接口libevent

	if (!ret) {
		std::cout << "NetworkInterface  server is start failed\n";
		return -1;
	}

	while (true)
	{
		NTIF->network_event_dispatch();
		sleep(2);
		LOG_DEBUG("NetworkInterface is Wait for request \n");
	}

	//MobileCodeReqEv* pmcre = new MobileCodeReqEv("18899666699");
	//DMS->enqueue(pmcre);

	sleep(4);
	DMS->close();
	sleep(3);

	return 0;
}